package com.cqcj.login.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //把ServletRequest转换成HttpServletRequest类型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取资源路径
        String uri = request.getRequestURI();
        //1.判断访问资源是否是登录资源(验证码，注册，登录)
        //是登录资源放行
        if(uri.contains("checkCodeServlet")||uri.contains("RegisterService")||uri.contains("RegisterServlet")|| uri.contains("register.jsp")||uri.contains("login.jsp") || uri.contains("/loginServlet") || uri.contains("LoginService") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/imgs/")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {//不是登录资源就跳就验证是否登录
            //2.判断用户是否登录
            HttpSession session = request.getSession();
            Object user = session.getAttribute("user");
            if(user != null){//用户登录，放行
                filterChain.doFilter(servletRequest,servletResponse);
            }else {//没登录跳转到登录页面（转发）
                request.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            }
        }
    }
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
